package com.hefan.live.service;

import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.live.dao.LiveLogDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.live.bean.LiveLog;
import com.hefan.live.bean.LivingHeartBeatVo;
import com.hefan.live.itf.LiveLogService;
import com.hefan.live.itf.LivingHeartBeatMonitorService;
import com.hefan.live.itf.LivingRedisOptService;

/**
 * 直播间心跳监听任务
 *
 * @author kevin_zhang
 */
@Path("/live")
@Component("livingHeartBeatMonitorService")
public class LivingHeartBeatMonitorServiceImpl implements LivingHeartBeatMonitorService {
    Logger logger = LoggerFactory.getLogger(LivingHeartBeatMonitorServiceImpl.class);

    @Resource
    JedisService jedisService;
    @Resource
    LiveLogService liveLogService;
    @Resource
    LiveLogDao liveLogDao;
    @Resource
    LivingRedisOptService livingRedisOptService;

    @GET
    @Path("/heartBeatMonitor")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public void livingHeartBeatMonitorOpreate() {
        logger.info("直播间心跳监听任务－－start");
        try {
            List<LiveLog> livingList = liveLogDao.getLivingLiveLogList();
            if (null != livingList && livingList.size() > 0) {
                for (LiveLog liveLog : livingList) {
                    if (liveLog.getIsVipLive() == 0) {
                        try {
                            String infoRedis = livingRedisOptService.getLivingHeartBeatInfo(liveLog.getLiveUuid());
                            logger.info("直播间心跳监听任务－－infoRedis=" + infoRedis);
                            long currentTime = System.currentTimeMillis();
                            if (StringUtils.isNotBlank(infoRedis)) {
                                LivingHeartBeatVo livingHeartBeatVo = JSON.parseObject(infoRedis, LivingHeartBeatVo.class);
                                if (null != livingHeartBeatVo && livingHeartBeatVo.getChatRoomId() > 0
                                        && StringUtils.isNotBlank(livingHeartBeatVo.getLiveUuid())
                                        && StringUtils.isNotBlank(livingHeartBeatVo.getAuthoruserId())
                                        && livingHeartBeatVo.getUpdateTime() > 0) {
                                    // 超时关闭直播间
                                    if ((currentTime - livingHeartBeatVo.getUpdateTime()) >= (60 * 1000)) {
                                        closeLivingRoom(liveLog.getLiveUuid());
                                    }
                                } else {
                                    logger.info("直播间心跳监听任务－－本次任务执行失败：参数校验不通过：" + infoRedis);
                                }
                            } else {
                                if (null != liveLog.getStartTime()
                                        && (currentTime - liveLog.getStartTime().getTime() >= 2 * 60 * 1000)) {
                                    // 2分钟超时关闭直播间
                                    logger.info("直播间心跳监听任务－－该直播超过2分钟未关闭，启动关闭中：" + "LiveUuid=" + liveLog.getLiveUuid());
                                    closeLivingRoom(liveLog.getLiveUuid());
                                    logger.info("直播间心跳监听任务－－该直播超过2分钟未关闭，启动关闭结束：" + "LiveUuid=" + liveLog.getLiveUuid());
                                } else {
                                    logger.info("直播间心跳监听任务－－redis未读取到 ：" + liveLog.getLiveUuid());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.info("直播间心跳监听任务－－执行失败：" + e.getMessage().toString());
                        }
                    }
                }
            } else {
                logger.info("直播间心跳监听任务－－本次任务执行结束：暂无在线直播数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("直播间心跳监听任务－－执行失败：" + e.getMessage().toString());
        } finally {
            logger.info("直播间心跳监听任务－－end");
        }
    }

    /**
     * 关闭直播间
     *
     * @param liveUuid
     */
    @SuppressWarnings("rawtypes")
    private void closeLivingRoom(String liveUuid) {
        try {
            // 关闭直播间
            ResultBean resultBean = liveLogService.liveExcEnd(liveUuid,2,"");
            if (null == resultBean || resultBean.getCode() < 0) {
                logger.info("直播间心跳监听任务－－直播间关闭失败，无返回，参数：liveUuid＝" + liveUuid + "  type=" + 2);
            } else {
                if (resultBean.getCode() == ResultCode.SUCCESS.get_code()) {
                    logger.info("直播间心跳监听任务－－直播间 " + liveUuid + " 关闭成功");
                } else {
                    logger.info("直播间心跳监听任务－－直播间 " + liveUuid + " 关闭失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("直播间心跳监听任务－－关闭直播间失败：" + e.getMessage().toString());
        }
    }
}
